package bad;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class Race {
    public static void main(String[] args) {

//A一定要等Ｂ跑完至少十步后气跑
//Ａ最终一定到领先Ｂ至少十步
        ReentrantLock lock = new ReentrantLock();
        Condition condition = lock.newCondition();
        ReentrantLock lock2 = new ReentrantLock();
        Condition condition2 = lock2.newCondition();
        AtomicInteger k = new AtomicInteger();
        new Thread(() -> {
            int i ;
            lock.lock();
            try {
                condition.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                lock.unlock();
            }

            for (i = 0; i < 100; i++) {
                SomeTopic.debug(String.format("跑步中。。。。%03d", i));
            }
            k.set(i);
//      event      i==99
            lock2.lock();
            try{
                condition2.signal();
            }finally {
                lock2.unlock();
            }

        }, "A").start();
        new Thread(() -> {
            int i;
            for (i = 0; i < 10; i++) {
                SomeTopic.debug(String.format("跑步中。。。。%03d", i));
            }
//            i==9;
            lock.lock();
            try {
                condition.signal();
            } finally {
                lock.unlock();
            }

            for (; i < 80; i++) {
                SomeTopic.debug(String.format("跑步中。。。。%03d", i));
            }

            lock2.lock();
            try{
                condition2.await();
            }catch (Exception e){
                e.printStackTrace();
            }finally {
                lock2.unlock();
            }
            SomeTopic.debug(String.format("呀，Ａ已经跑步到第。。。。%03d", k.get()));
            for (; i < 100; i++) {
                SomeTopic.debug(String.format("跑步中。。。。%03d", i));
            }
        }, "B").start();
    }
}
